package com.uniview.weblog1;

import com.uniview.config.GatewayConstants;
import com.uniview.filter.context.GatewayContext;
import com.uniview.service.AccessLogService;
import lombok.extern.slf4j.Slf4j;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * @Author lux
 * @date: 2019/12/10
 * @desc: 日志处理过滤器 处理业务错误日志以及正确日志，全部都会走到这里来
 */
@Slf4j
public class AccessLogFilter implements GlobalFilter,Ordered {
    @Autowired
    AccessLogService accessLogService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        GatewayContext gatewayContext = exchange.getAttribute(GatewayContext.CACHE_GATEWAY_CONTEXT);
        DataBufferFactory bufferFactory = response.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.map(dataBuffer -> {
                        // probably should reuse buffers
                        byte[] content = new byte[dataBuffer.readableByteCount()];
                        dataBuffer.read(content);
                        //打印返回信息
                        String responseData = new String(content, Charset.forName("UTF-8"));
                        gatewayContext.setResponseBody(responseData);
                        exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT,gatewayContext);
                         log.info("响应内容:{}",responseData);
                         byte[] uppedContent = new String(content, Charset.forName("UTF-8")).getBytes();
                        //释放掉内存
                        DataBufferUtils.release(dataBuffer);
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                // if body is not a flux. never got there.
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build()).then(Mono.fromRunnable(()->{
            accessLogService.sendLog(exchange, null);
        }));
    }

    @Override
    public int getOrder() {
        return GatewayConstants.ACCESS_LOG_ORDER;
    }
}

